import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { UpdateUserDto } from '../dto/update-user.dto';
import { AppI18nService } from '../../i18n/i18n.service';

@Injectable()
export class UsersService {
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        private readonly i18nService: AppI18nService,
    ) { }

    /**
     * 根据ID查找用户
     */
    async findById(id: number, language = 'en'): Promise<User> {
        const user = await this.userRepository.findOne({ where: { id } });
        if (!user) {
            const message = this.i18nService.getUserMessage('not_found', {}, language);
            throw new NotFoundException(message);
        }
        return user;
    }

    /**
     * 根据钱包地址查找用户
     */
    async findByWallet(walletAddress: string, language = 'en'): Promise<User> {
        const user = await this.userRepository.findOne({
            where: { walletAddress: walletAddress },
        });
        if (!user) {
            const message = this.i18nService.getUserMessage('not_found', {}, language);
            throw new NotFoundException(message);
        }
        return user;
    }

    /**
     * 更新用户信息
     */
    async updateUser(id: number, updateUserDto: UpdateUserDto, language = 'en'): Promise<User> {
        const user = await this.findById(id, language);

        Object.assign(user, updateUserDto);

        return await this.userRepository.save(user);
    }

    /**
     * 检查用户是否存在
     */
    async exists(walletAddress: string): Promise<boolean> {
        const count = await this.userRepository.count({
            where: { walletAddress: walletAddress },
        });
        return count > 0;
    }

    /**
     * 获取用户列表（管理员功能）
     */
    async findAll(page = 1, limit = 10): Promise<{ users: User[]; total: number }> {
        const [users, total] = await this.userRepository.findAndCount({
            skip: (page - 1) * limit,
            take: limit,
            order: { createdAt: 'DESC' },
        });

        return { users, total };
    }
}
